package com.xiaozhichao.jarslink.main.config;

import com.alipay.jarslink.api.Module;
import com.alipay.jarslink.api.ModuleConfig;
import com.alipay.jarslink.api.ModuleLoader;
import com.alipay.jarslink.api.ModuleManager;
import com.alipay.jarslink.api.impl.AbstractModuleRefreshScheduler;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class ModuleRefreshSchedulerImpl extends AbstractModuleRefreshScheduler {

    private static final String PATH = "D:/work/git/jarslinkProject/";

    private ModuleLoader moduleLoader;
    private ModuleManager moduleManager;

    public ModuleRefreshSchedulerImpl(ModuleLoader moduleLoader, ModuleManager moduleManager){
        this.setModuleManager(moduleManager);
        this.setModuleLoader(moduleLoader);

    }

    public ModuleRefreshSchedulerImpl(){

    }

    @Override
    public List<ModuleConfig> queryModuleConfigs() {
        List<ModuleConfig> configList = new ArrayList<>();
        Map<String,List<String>> moduleInfos = null;
        try {
            moduleInfos =  ModuleScanner.doScan(PATH);
            Iterator<Map.Entry<String, List<String>>> it = moduleInfos.entrySet().iterator();
            while (it.hasNext()){
                Map.Entry<String, List<String>> entry = it.next();
                List<String> values = entry.getValue();
                ModuleConfig moduleConfig = new ModuleConfig();
                //URL demoModule = Thread.currentThread().getContextClassLoader().getResource(paras[0]); 相对路径 classpath
                URL demoModule = new URL("file", "", -1, values.get(0));
                moduleConfig.setName(values.get(1));
                moduleConfig.setEnabled(true);
                moduleConfig.setVersion(values.get(2));
                moduleConfig.setModuleUrl(ImmutableList.of(demoModule));
                //决定是否走注解扫描还是xml  加了这个是自动扫描注解 未加则是xml读取
                /*moduleConfig.addScanPackage(values.get(3));*/
                moduleConfig.withNeedUnloadOldVersion(true);
                configList.add(moduleConfig);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(moduleInfos != null){
                moduleInfos.clear();
            }
            return configList;
        }
    }

}
